package com.kcl.dfss;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.kcl.dfss.http.ServerConnection;

public class SelectCarActivity extends Activity {

	protected static final String tag = "SelectCarActivity";
	private LinearLayout layout_index;
	private ListView car_list;
	private ProgressBar progress_car;
	
	private String[] str = {"A", "B", "C", "D", "F", "G", "H", "J",
			"K", "L", "M", "N", "O", "Q","R","S","T","W", "X", "Y", "Z" };
	private String[] data = {};	//数据
	private String[] braid = {}; //车型Id
	private String[] indexdata = {};	//整合了索引字母之后的数据
	private HashMap<String, Integer> selector;
	private TextView text_index;	//中间显示的文本
	private int height;
	private List<HashMap<String, String>> list ;
	CarAdapter carAdapter;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_select_car);

		SharedPreferences preferences = getSharedPreferences("shared_login", 0);
		final String userid = preferences.getString("userid", "");
		
		progress_car = (ProgressBar) findViewById(R.id.progress_car);
		
		final Handler handler = new Handler(){

			@Override
			public void handleMessage(Message msg) {
				if(msg.what == 1){
					sortIndex();
					car_list = (ListView) findViewById(R.id.car_list);
					carAdapter = new CarAdapter(SelectCarActivity.this);
					car_list.setAdapter(carAdapter);
					progress_car.setVisibility(View.GONE);
					car_list.setOnItemClickListener(new OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> parent, View view,
								int position, long id) {
							Intent intent = new Intent();
							intent.putExtra("braId", indexdata[position].substring(indexdata[position].indexOf(",")+1));
							intent.putExtra("carname", indexdata[position].substring(3,indexdata[position].indexOf(",")));
							intent.setClass(SelectCarActivity.this, SeclectSeriesActivity.class);
							startActivity(intent);
						}
					});
					getIndexView();
				}
			}
			
		};
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				String result = ServerConnection.GetBrald(userid);
				try {
					JSONObject jsonObject = new JSONObject(result);
					JSONArray jsonArray = jsonObject.getJSONArray("data");
				
					data = new String[jsonArray.length()];
					list = new ArrayList<HashMap<String,String>>();
					HashMap<String, String> map = null;
					for(int i=0;i<jsonArray.length();i++){
						JSONObject jo = (JSONObject) jsonArray.opt(i);
						data[i] = jo.getString("braname")+","+jo.getString("braId");
						map = new HashMap<String, String>();
						map.put("braname", jo.getString("braname"));
						map.put("initials", jo.getString("initials"));
						map.put("braId", jo.getString("braId"));
						list.add(map);
					}
					Log.i(tag,"data数组："+ Arrays.toString(data));
					Message message = new Message();
					message.what = 1;
					handler.sendMessage(message);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}).start();
		LinearLayout select_car_back = (LinearLayout) findViewById(R.id.select_car_back);
		select_car_back.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		layout_index = (LinearLayout) findViewById(R.id.layout_index);
		layout_index.setBackgroundColor(Color.parseColor("#00ffffff"));
		
		text_index = (TextView) findViewById(R.id.text_index);
		text_index.setVisibility(View.INVISIBLE);
		
	}
	
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		// TODO Auto-generated method stub
		height = layout_index.getHeight()/str.length;
//		getIndexView();
	}
	
	//获取排序后的数据
	public void sortIndex(){
		
		TreeSet<String> set = new TreeSet<String>();
		//获取初始化数据源中的首字母，添加到set中
		for(String string:data){
			set.add(String.valueOf(string.charAt(0)));
		}
		//新数组的长度为原数据加上set的大小
		indexdata = new String[data.length+set.size()];
		int i = 0;
		for(String string:set){
			indexdata[i] = string;
			i++;
		}
		// 将原数据拷贝到新数据中
		System.arraycopy(data, 0, indexdata, set.size(), data.length);
		// 按照首字母排序
		Log.i(tag, "未排序的indexdata:"+Arrays.toString(indexdata));
		Arrays.sort(indexdata,String.CASE_INSENSITIVE_ORDER);
	}
	
	//绘制索引列表
	public void getIndexView(){
		LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,height);
		for(int i=0;i<str.length;i++){
			final TextView tv = new TextView(this);	//LinearLayout中显示的索引字母
			tv.setLayoutParams(params);
			tv.setText(str[i]);
			tv.setTextColor(Color.parseColor("#c8dadf"));
			tv.setPadding(10, 0, 10, 0);
			layout_index.addView(tv);
			layout_index.setOnTouchListener(new OnTouchListener() {
				
				@SuppressLint("ClickableViewAccessibility")
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					float y = event.getY();
					int index = (int) (y/height);
					if(index > -1 && index < str.length){	//防止越界
						String key = str[index];
						if(selector.containsKey(key)){
							int pos = selector.get(key);
							if(car_list.getHeaderViewsCount()>0){
								car_list.setSelectionFromTop(pos+car_list.getHeaderViewsCount(), 0);
							}else{
								car_list.setSelectionFromTop(pos, 0);
							}
							text_index.setVisibility(View.VISIBLE);
							text_index.setText(str[index]);
						}
					}
					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						layout_index.setBackgroundColor(Color.parseColor("#606060"));
						break;
					case MotionEvent.ACTION_MOVE:
						
						break;
					case MotionEvent.ACTION_UP:
						layout_index.setBackgroundColor(Color.parseColor("#00ffffff"));
						text_index.setVisibility(View.INVISIBLE);
						break;
					}
					return true;
				}
			});
		}
	}


	private class CarAdapter extends BaseAdapter{
		
		Context context;
		
		@SuppressLint("DefaultLocale")
		public CarAdapter(Context context){
			this.context = context;
			selector = new HashMap<String, Integer>();
			for(int j=0;j<str.length;j++){
				for(int i=0;i<indexdata.length;i++){
					if(indexdata[i].equals(str[j])){
						selector.put(str[j], i);
					}
				}
			}
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return indexdata.length;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return indexdata[position];
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}
		
		@Override
		public boolean isEnabled(int position) {
			if(indexdata[position].length() == 1){	//如果是字母索引表示不能点击
				return false;
			}
			return super.isEnabled(position);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			String[] copyindex = new String[indexdata.length];
			for(int i=0;i<indexdata.length;i++){
				if(indexdata[i].length() == 1){
					copyindex[i] = indexdata[i];
				}else{
					copyindex[i] = indexdata[i].substring(3,indexdata[i].indexOf(","));					
				}
			}
			String item = copyindex[position];
			if(item.length() == 1){
				convertView = getLayoutInflater().inflate(R.layout.select_car_title, null);
				TextView text_letter = (TextView) convertView.findViewById(R.id.text_letter);
				text_letter.setText(item);
			}else{
				convertView = getLayoutInflater().inflate(R.layout.select_car_item, null);
				TextView text_carname = (TextView) convertView.findViewById(R.id.text_carname);
				text_carname.setText(item);
			}
			return convertView;
		}
		
	}
	
}
